package hu.ngms.jpf.maven;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

public class JUnitWrapper {
	
	private JUnitCore jUnitCore;
	
	
	public JUnitWrapper() {
		jUnitCore = new JUnitCore();
	}
	
	public void delegateTestRunning(String... classNames) {
		Class<?>[] classes = loadClasses(classNames);
		
		jUnitCore.addListener(new RunListener() {
			
			@Override
			public void testRunFinished(Result result) throws Exception {
				if (!result.wasSuccessful()) {
					StringBuilder sb = new StringBuilder();
					for (Failure f : result.getFailures()) {
						sb.append(f.getDescription().getClassName()).append(".")
							.append(f.getDescription().getMethodName()).append("\n");
						sb.append(f.getTrace()).append("\n");
					}
					throw new AssertionError(sb.toString());
				}
			}

		});
		jUnitCore.run(classes);
	}

	private Class<?>[] loadClasses(String... classNames) {
		Class<?>[] classes = new Class[classNames.length];
		for (int i = 0; i < classes.length; i++) {
			try {
				classes[i] = Class.forName(classNames[i]);
			} catch (ClassNotFoundException e) {
				throw new IllegalArgumentException(e);
			}
		}
		return classes;
	}
	
	public static void main(String[] args) {
		String[] classNames = args;
		if (args.length == 0) {
			throw new IllegalArgumentException("Missing unit test classes");
		}
		new JUnitWrapper().delegateTestRunning(classNames);
	}

}
